package com.airbnb.mvrx.sample.core

import android.app.Application
import android.content.Context
import android.os.Environment
import android.support.multidex.MultiDex
import com.airbnb.mvrx.sample.Utils
import com.airbnb.mvrx.sample.network.BooklnService
import com.airbnb.mvrx.sample.network.DadJokeService
import com.facebook.drawee.backends.pipeline.Fresco
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Cache
import okhttp3.OkHttpClient
import org.koin.android.ext.android.startKoin
import org.koin.dsl.module.Module
import org.koin.dsl.module.applicationContext
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import timber.log.Timber
import timber.log.Timber.DebugTree
import java.io.File


class UpApplication : Application() {

    val BASE_URL = "https://wxmini-prepub.bookln.cn"

    private val dadJokeServiceModule: Module = applicationContext {
        bean {
            val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
            val retrofit = Retrofit.Builder()
                    .baseUrl("https://icanhazdadjoke.com/")
                    .addConverterFactory(MoshiConverterFactory.create(moshi))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
            retrofit.create(DadJokeService::class.java)
        }
    }

    private val booklnServiceModule: Module = applicationContext {
        bean {
            val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
            val cacheDir = Utils.format("%s/Android/data/%s/cache", Environment.getExternalStorageDirectory(), packageName)
            //cache
            val client = OkHttpClient.Builder()
                    .cache(Cache(File(cacheDir), (10 * 1024 * 1024).toLong())) // 10 MB
                    .addInterceptor { chain ->
                        var request = chain.request()
                        request = if (isConnected()) {
                            request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build()
                        } else {
                            request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build()
                        }
                        chain.proceed(request)
                    }
                    .build()
            //
            val retrofit = Retrofit.Builder()
//                    .baseUrl("https://dailys.bookln.cn/")
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(MoshiConverterFactory.create(moshi))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
            retrofit.create(BooklnService::class.java)
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        startKoin(this, listOf(dadJokeServiceModule, booklnServiceModule))
        Fresco.initialize(this)
        Timber.plant(DebugTree())
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }


    companion object {
        private var instance: UpApplication? = null
        fun getApp() = instance!!
    }

    fun isConnected(): Boolean {
        try {
            val e = getSystemService(
                    Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
            val activeNetwork = e.activeNetworkInfo
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return false
    }


}